import os
import time
from colorlog import ColoredFormatter
import logging
from SelfStudy.FrameWork.ApiIhrmpytest.config import BASE_DIR
# 定义日志文件存放目录
LOG_DIR = os.path.join(BASE_DIR, "logs")
if not os.path.exists(LOG_DIR):
    os.makedirs(LOG_DIR)

# 时间戳日志文件名（仅生成一次）
LOG_FILE_NAME = time.strftime("%Y-%m-%d_%H-%M-%S") + ".log"
LOG_FILE_PATH = os.path.join(LOG_DIR, LOG_FILE_NAME)

# 全局 logger 单例
_global_logger = None

def get_logger():
    global _global_logger
    if _global_logger:
        return _global_logger

    logger = logging.getLogger("global_test_logger")
    logger.setLevel(logging.DEBUG)

    # 避免重复添加 handler
    if not logger.handlers:
        # 文件处理器
        file_handler = logging.FileHandler(LOG_FILE_PATH, encoding="utf-8")
        file_formatter = logging.Formatter(
            "%(asctime)s [%(levelname)s] %(filename)s:%(lineno)d - %(message)s",
            datefmt="%Y-%m-%d %H:%M:%S"
        )
        file_handler.setFormatter(file_formatter)
        logger.addHandler(file_handler)

        # 控制台彩色输出
        console_handler = logging.StreamHandler()
        color_formatter = ColoredFormatter(
            fmt="%(log_color)s%(asctime)s [%(levelname)s] %(filename)s:%(lineno)d - %(message)s",
            datefmt="%H:%M:%S",
            log_colors={
                'DEBUG': 'cyan',
                'INFO': 'green',
                'WARNING': 'yellow',
                'ERROR': 'red',
                'CRITICAL': 'red,bg_white',
            },
            style='%'
        )
        console_handler.setFormatter(color_formatter)
        logger.addHandler(console_handler)

    _global_logger = logger
    return logger
